<?php

namespace app\api\controller;

use app\admin\model\Activity;
use app\admin\model\Banner;
use app\admin\model\Deliverytime;
use app\admin\model\Refundreason;
use app\admin\model\Video;
use app\api\model\Carts;
use app\common\controller\Api;
use addons\crontab\model\Crontab;
use Cron\CronExpression;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 执行定时任务
     */
    public function task()
    {
        $withPcntl = false;
        $pool = null;

        $config = get_addon_config('crontab');
        $mode = $config['mode'] ?? 'pcntl';
        if ($mode == 'pcntl' && function_exists('pcntl_fork')) {
            $withPcntl = true;
            $pool = new \Jenner\SimpleFork\Pool();
        }

        $time = time();
        $logDir = LOG_PATH . 'crontab' . DS;
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755);
        }
        //筛选未过期且未完成的任务
        $crontabList = Crontab::where('status', '=', 'normal')->order('weigh DESC,id DESC')->select();
        $execTime = time();
        foreach ($crontabList as $crontab) {
            $update = [];
            $execute = false;
            if ($time < $crontab['begintime']) {
                //任务未开始
                continue;
            }
            if ($crontab['maximums'] && $crontab['executes'] > $crontab['maximums']) {
                //任务已超过最大执行次数
                $update['status'] = 'completed';
            } else {
                if ($crontab['endtime'] > 0 && $time > $crontab['endtime']) {
                    //任务已过期
                    $update['status'] = 'expired';
                } else {
                    //重复执行
                    //如果未到执行时间则继续循环
                    $cron = CronExpression::factory($crontab['schedule']);
                    if (!$cron->isDue() || ($execTime && date("YmdHi", $execTime) === date("YmdHi", $crontab['executetime']))) {
                        continue;
                    }
                    $execute = true;
                }
            }

            // 如果允许执行
            if ($execute) {
                $update['executetime'] = $time;
                $update['executes'] = $crontab['executes'] + 1;
                $update['status'] = ($crontab['maximums'] > 0 && $update['executes'] >= $crontab['maximums']) ? 'completed' : 'normal';
            }

            // 如果需要更新状态
            if (!$update) {
                continue;
            }
            // 更新状态
            $crontab->save($update);
            Db::connect()->close();
            // 将执行放在后面是为了避免超时导致多次执行
            if (!$execute) {
                continue;
            }

            $runnable = new \addons\crontab\library\CommandRunnable($crontab);
            if ($withPcntl) {
                $process = new \Jenner\SimpleFork\Process($runnable);
                $name = $crontab['title'];
                $pool->execute($process);
            } else {
                $runnable->run();
            }

        }
        if ($withPcntl && $pool) {
            $pool->wait();
        }
        return "Execute completed!\n";
    }

    public function task2()
    {
        $date = date('Y-m-d',time());

        Carts::destroy(['date'=>['<=',$date]]);

        $this->success();
    }

    /**
     * 配置
     *
     */
    public function config()
    {
        $data = [
            'member_discount'=>\app\common\model\Config::get(['name'=>'member_discount'])->value,
            'incubator_deposit'=>\app\common\model\Config::get(['name'=>'incubator_deposit'])->value,
            'name'=>\app\common\model\Config::get(['name'=>'name'])->value,
            'policy'=>\app\common\model\Config::get(['name'=>'policy'])->value,
            'privacy_agreement'=>\app\common\model\Config::get(['name'=>'privacy_agreement'])->value,
            'brand_introduction'=>\app\common\model\Config::get(['name'=>'brand_introduction'])->value,
            'advertising_map'=>\app\common\model\Config::get(['name'=>'advertising_map'])->value,
            'incubator_copywriting'=>\app\common\model\Config::get(['name'=>'incubator_copywriting'])->value,
            'starting_price'=>\app\common\model\Config::get(['name'=>'starting_price'])->value,
            'cut_off_time'=>\app\common\model\Config::get(['name'=>'cut_off_time'])->value,
            'ordering_area_img'=>\app\common\model\Config::get(['name'=>'ordering_area_img'])->value,
            'user_center_img'=>\app\common\model\Config::get(['name'=>'user_center_img'])->value,
            'kitchen_img'=>\app\common\model\Config::get(['name'=>'kitchen_img'])->value,
            'served_template_id'=>\app\common\model\Config::get(['name'=>'served_template_id'])->value,
        ];

        $this->success('请求成功',$data);
    }

    //轮播
    public function banner()
    {
        $type = input('type',0);

        $list = Banner::where(['type'=>$type])->order('weigh desc')->select();

        $this->success('',$list);

    }

    //视频
    public function video()
    {
        $list = Video::order('weigh desc')->select();

        $this->success('',$list);

    }

    //营销活动
    public function activity()
    {
        $list = Activity::order('weigh desc')->select();

        $this->success('',$list);

    }

    public function activityDetail()
    {
        $id = input('id',0);

        $detail = Activity::get($id);

        $this->success('',$detail);
    }


    //退款原因
    public function reason()
    {
        $list = Refundreason::order('weigh desc')->select();
        $this->success('',$list);
    }

    //配送时间
    public function deliverytime()
    {
        $list = Deliverytime::order('start_time asc')->select();
        $this->success('',$list);
    }

    //微信审核开关
    public function examine()
    {
        $wx_examine_status = Config('site.wx_examine_status');
        $this->success('成功', [
            'wx_examine_status' => $wx_examine_status,
        ]);
    }
}
